package com.wh.wisdomsite.xbox.server;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wh.wisdomsite.xbox.ba.entity.AppMethod;
import com.wh.wisdomsite.xbox.ba.entity.AppSecret;
import com.wh.wisdomsite.xbox.ba.entity.ServiceMethod;
import com.wh.wisdomsite.xbox.ba.service.IAppMethodService;
import com.wh.wisdomsite.xbox.ba.service.IAppSecretService;
import com.wh.wisdomsite.xbox.ba.service.IServiceMethodService;
import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.ServiceMethodHandler;
import com.wh.wisdomsite.xbox.common.reponse.CommonResult;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.core.ServiceDispatcher;

import com.wh.wisdomsite.xbox.core.model.SignRule;

import com.wh.wisdomsite.xbox.server.util.XboxRequestContextFilter;
import com.wh.wisdomsite.xbox.utils.Base64;
import com.wh.wisdomsite.xbox.utils.encrypt.hmacSHA1.HmacSHA1;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Google;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 功能描述：请求测试
 * @Package com.wh.wisdomsite.xbox.server
 * @author 谢泽鹏
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/request")
public class requestController {

    private static final Log logger = LogFactory.getLog(requestController.class);

    @Resource(name = "serviceDispatcher")
    private ServiceDispatcher serviceDispatcher;

    @Autowired
    private IServiceMethodService iServiceMethodService;

    @Autowired
    private IAppSecretService iAppSecretService;

    @Autowired
    private IAppMethodService iAppMethodService;

    /**
     * 跳转页面
     * @return
     */
    @RequiresPermissions("rules:dataServices_request_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String requestPageList() {
        return "/dataServices/request/requestPage";
    }



    /**
     * 加载应用秘钥Key
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "loadAppKey.do", method = RequestMethod.GET)
    public void loadAppKey(HttpServletResponse response) throws Exception {
        EntityWrapper<AppSecret> ewAppSecret = new EntityWrapper<AppSecret>();
        ewAppSecret.setEntity(new AppSecret());
        List<AppSecret> appSecrets = iAppSecretService.selectList(ewAppSecret);
        String appSecretList = JSON.toJSONString(appSecrets);
        ResManager.getTextOut(response).print(appSecretList);
    }


    /**
     * 加载方法
     * @param appKey
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "loadAppMethod.do", method = RequestMethod.GET)
    public void loadAppMethod(String appKey, HttpServletResponse response) throws Exception {
        EntityWrapper<AppMethod> ewAppMethod = new EntityWrapper<AppMethod>();
        ewAppMethod.setEntity(new AppMethod());
        ewAppMethod.eq("T_APP_KEY", appKey);
        ewAppMethod.orderBy("T_METHOD", true);
        List<AppMethod> appMethods = iAppMethodService.selectList(ewAppMethod);
        List<String> methodList = new ArrayList<String>();
        for (AppMethod appMethod : appMethods) {
            methodList.add(appMethod.getMethod().substring(0, appMethod.getMethod().indexOf("$")));
        }
        String appSecretList = JSON.toJSONString(methodList);
        ResManager.getTextOut(response).print(appSecretList);
    }


    /**
     * 加载版本号
     * @param method
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "loadVersion.do", method = RequestMethod.GET)
    public void loadVersion(String method, HttpServletResponse response) throws Exception {
        EntityWrapper<ServiceMethod> ewServiceMethod = new EntityWrapper<ServiceMethod>();
        ewServiceMethod.setEntity(new ServiceMethod());
        ewServiceMethod.eq("T_METHOD", method);
        List<ServiceMethod> serviceMethods = iServiceMethodService.selectList(ewServiceMethod);
        List<String> versionList = new ArrayList<String>();
        for (ServiceMethod sm : serviceMethods) {
            versionList.add(sm.getVersion());
        }
        String appSecretList = JSON.toJSONString(versionList);
        ResManager.getTextOut(response).print(appSecretList);
    }


    /**
     * 生成参数模型
     * @param method
     * @param version
     * @param response
     */
    @RequestMapping(value = "createBindObject.do", method = RequestMethod.GET)
    public void createBindObject(String method, String version, HttpServletResponse response) {
        CommonResult commonResult = new CommonResult();
        try {
            logger.info("生成参数模型-->>开始");
            Map<String, ServiceMethodHandler> serviceMethodHandlerMap = serviceDispatcher.getXboxContext().getServiceHandlerMap();
            ServiceMethodHandler serviceMethodHandler = serviceMethodHandlerMap.get(method + "$" + version);
            Class clazz = serviceMethodHandler.getRequestType();
            Object object = clazz.newInstance();
            String result = JSON.toJSONString(object, new XboxRequestContextFilter(), SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);
            commonResult.setCode(Constants.CODE_SUCCESS);
            commonResult.setResult(result);
            commonResult.setMessage("生成参数模型成功");
            ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
        } catch (Exception e) {
            try {
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setResult("");
                commonResult.setMessage("参数模型生成失败");
                ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            logger.error("生成参数模型-->>Exception " + e.getMessage());
        }
        logger.info("生成参数模型-->>结束");
    }


    /**
     * 生成签名
     * @param response
     */
    @RequestMapping(value = "createSign.do", method = RequestMethod.POST)
    public void createSign(HttpServletRequest request, HttpServletResponse response) {
        CommonResult commonResult = new CommonResult();
        try{
            logger.info("生成签名-->>开始");

            //获取参数
            String client = request.getParameter("client");
            String callType = request.getParameter("callType");
            String callVersion = request.getParameter("callVersion");
            String appkey = request.getParameter("appkey");
            String format = request.getParameter("format");
            String method = request.getParameter("method");
            String version = request.getParameter("version");
            String appBrand = request.getParameter("appBrand");
            String appBaseInfo = request.getParameter("appBaseInfo");
            String bindObject = request.getParameter("bindObject");
            String sessionId = request.getParameter("sessionId");

            SignRule signRule = new SignRule();
            /**
             * 1: 九项基本参数 + 两项业务参数
             */
            signRule.setAppKey(appkey);
            signRule.setBindObject(bindObject.replaceAll("\r|\n|\t", ""));
            signRule.setCallType(callType);
            signRule.setCallVersion(callVersion);
            signRule.setClient(client);
            signRule.setFormat(format);
            signRule.setMethod(method);
            signRule.setSessionId(sessionId);
            signRule.setVersion(version);
            signRule.setAppBrand(appBrand);
            signRule.setAppBaseInfo(appBaseInfo);

            //获取签名报文
            String signString = JsonUtil_Google.getJsonStringByObject(signRule);
            logger.info("createSign-->>签名报文signString :" + signString);

            //获取签名结果
            String signStr = HmacSHA1.Encrypt(signString, Constants.ZSD_COMPANY_SERVER_MESSAGE_PASSWORD);
            String signValue = Base64.encodeToString(signStr.getBytes(), 2);
            logger.info("createSign-->>签名密码signValue :" + signValue);

            commonResult.setCode(Constants.CODE_SUCCESS);
            commonResult.setResult(signValue);
            commonResult.setMessage("生成签名成功");
            ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
        }catch (Exception e){
            e.printStackTrace();
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setResult("");
            commonResult.setMessage("生成签名失败");
            ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
        }
            logger.info("生成签名-->>结束");
    }


}
